import React from 'react';
import {
    Row,
    Col,
    Form,
    Input,
    Select,
    Button,
    DatePicker,
    message
} from 'antd';
import axios from 'axios';
import intercept from '../../../utils/intercept';
import { config } from 'utils';
import format from './format';
import '../less/Rent.less';
const FormItem = Form.Item;
const Option = Select.Option;
const AMap = window.AMap;


class RentBills extends React.Component {
    constructor(props) {
        super(props);
        const user = JSON.parse(sessionStorage.getItem("user"));
        this.state = {
            user: user.UserName,
            lineId: '',
            lineData: {},
            carpoolingPrice: 0,
            textInput: null,
            // sharing: "true"
        };
    };

    componentDidMount() {
        this.getLine();
        try {
            //输入提示
            this.getPosition();
        } catch (err) {
            window.location.reload();
        }
    };
    // 高德地图input输入提示
    getPosition = () => {
        var departSite = new window.AMap.Autocomplete({
            input: 'departSite'
        });
        var EndSite = new window.AMap.Autocomplete({
            input: 'EndSite'
        });
        window.AMap.event.addListener(departSite, "select", selectD);//注册监听，当选中某条记录时会触发
        window.AMap.event.addListener(EndSite, "select", selectE);//注册监听，当选中某条记录时会触发
        function selectD(e) {
            if (e) {
                var DepartPosition = e.poi;
                if (!DepartPosition.location.lat || !DepartPosition.location.lng) {
                    message.warning("未获取到该地址的经纬度，请重新尝试！")
                    return
                }
                sessionStorage.setItem("DepartPosition", JSON.stringify(DepartPosition))
                let DepartPosition = JSON.parse(sessionStorage.getItem("DepartPosition"));
            }
        }
        function selectE(e) {
            if (e) {
                var EndPosition = e.poi;
                if (!EndPosition.location.lat || !EndPosition.location.lng) {
                    message.warning("未获取到该地址的经纬度，请重新尝试！")
                    return
                }
                sessionStorage.setItem('EndPosition', JSON.stringify(EndPosition))
            }
        }
    }

    getLine = () => {
        const token = sessionStorage.getItem("token");
        axios
            .get(`${config.api}Rental/GetCarLines?page=1&pageSize=10000000`, { headers: { Authorization: 'Bearer ' + token } })
            .then((data) => {
                // console.log(data)
                var lineList = data.data.pageList.collections;
                var lineNameId = [];

                lineList.map(function (val, index) {
                    lineNameId.push(<Option key={val.id}>{val.lineName}</Option>);
                })
                this.setState({
                    lineNameId: lineNameId,
                    lineData: data.data.pageList
                })
            })
            .catch(err => {
                intercept;
            })
    }

    // 线路选择后触发该函数
    getLineId(value) {
        let list = this.priceResult(value);
        this.refs.onePrice.value = list.carpoolingPrice;
        if (this.refs.personNumber.value.length == 0) {
            this.refs.personNumber.value = 1;
            this.refs.TPrice.value = list.carpoolingPrice;
        } else {
            this.refs.TPrice.value = this.refs.personNumber.value * list.carpoolingPrice;
        }
        this.setState({ lineId: value, FPrice: list.charteredPrice, TPrice: list.carpoolingPrice });
    }
    // 根据ID查找对象中符合条件的对象，已便于计算默认票价
    priceResult = (val) => {
        let data = this.state.lineData.collections;
        for (let i = 0; i < data.length; i++) {
            if (data[i].id == val) {
                return data[i]
            }
        }
    }
    isShare = (value) => {
        this.setState({
            isShare: value,
        });
    }
    // 约租类型选择后的出触发函数
    whetherSharing = (value) => {
        this.setState({ sharing: value })
        this.alert().then((res) => {
            if (res) {
                // 已经选择线路
                if (this.refs.personNumber.value.length == 0) {
                    this.refs.personNumber.value = 1;
                }
                if (value == "false") {
                    this.refs.onePrice.value = this.state.FPrice;
                    this.refs.TPrice.value = this.state.FPrice;
                } else {
                    this.refs.onePrice.value = this.state.TPrice;
                    this.refs.TPrice.value = this.refs.personNumber.value * this.state.TPrice;
                }
            } else {
                // 未选择线路

            }
        })


    }
    // “请先选择线路”提示
    async alert() {
        if (this.state.lineId.length == 0) {
            message.warning("请先选择线路")
            return false
        } else {
            return true
        }
    }
    // 此函数用于计算总价
    overPrice = () => {
        this.alert();
        // 人数
        let personN = this.refs.personNumber.value;
        // 总价
        let TPrice = this.refs.TPrice.value;
        // 价格/单价
        let onePrice = this.refs.onePrice.value;
        if (this.state.sharing == "true") {
            this.refs.TPrice.value = personN * onePrice;
        } else {
            this.refs.TPrice.value = this.refs.onePrice.value;
        }
    }
    // 清除非antd Input组件value值
    clear = () => {
        this.refs.departInput.value = "";
        this.refs.endInput.value = "";
        this.refs.personNumber.value = "";
        this.refs.onePrice.value = "";
        this.refs.TPrice.value = "";
    }
    handleReset = (e) => {
        this.props.form.resetFields();
        try {
            this.clear();
        } catch (err) { }
    }

    RentBillSubmit = (e) => {
        try {
            e.preventDefault();
            let DepartPosition = JSON.parse(sessionStorage.getItem("DepartPosition"));
            let EndPosition = JSON.parse(sessionStorage.getItem("EndPosition"));
            const token = sessionStorage.getItem("token");
            const params = this.props.form.getFieldsValue();
            // const user = this.state.user;
            console.log(DepartPosition)
            let departP = DepartPosition.district + DepartPosition.address + DepartPosition.name;
            let endP = EndPosition.district + EndPosition.address + EndPosition.name;
            if (!DepartPosition.location.lat || !DepartPosition.location.lng) {
                message.warning("出发地未获取到经纬度，请重新输入");
                return
            }
            if (!EndPosition.location.lat || !EndPosition.location.lng) {
                message.warning("目的地未获取到经纬度，请重新输入");
                return
            }
            if (departP && endP && params.RentBillName && params.BillName && params.CompilePhone && params.rentTime._d) {
                axios.post(`${config.api}Rental/ApplyTelOrder`, {
                    carLineid: params.RentBillName,
                    name: params.BillName, phone: params.CompilePhone, amount: this.refs.personNumber.value,
                    startPlace: departP, endPlace: endP, rentTime: format.format(params.rentTime._d),
                    orderType: this.state.sharing == "true" ? 1 : 0, price: this.refs.onePrice.value, priceAmount: this.refs.TPrice.value,
                    required: params.requires, isShare: params.rentTyle, startCoordinate: `${DepartPosition.location.lng},${DepartPosition.location.lat}`, endCoordinate: `${EndPosition.location.lng},${EndPosition.location.lat}`
                }, { headers: { Authorization: 'Bearer ' + token } }).then((data) => {
                    // console.log(data)
                    if (data.data.result) {
                        message.success('录单成功！');
                        this.props.form.resetFields();
                        try {
                            this.clear();
                        } catch (err) { console.log(err) }

                    } else {
                        message.warning(data.data.errorMessage)
                    }
                })
                    .catch(err => {
                        intercept;
                    })
            } else {
                message.warning('请查看录单信息是否填写完整')
            }
        } catch (err) {
            message.warning('请查看录单信息是否填写完整')
            // console.log(err)
        }
    }


    render() {
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 6
                }
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 14
                }
            }
        };
        const { getFieldDecorator } = this.props.form;
        const config = {
            rules: [{ type: 'object', required: true, message: 'Please select time!' }],
        };
        return (
            <div>
                <h2 className="RentBillTitle">电话录单</h2>
                <Form className="RentBillForm" onSubmit={this.RentBillSubmit}>
                    <Row>
                        <Col span={12}>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        线路名称
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('RentBillName', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写信息!',
                                        }
                                    ]
                                })(<Select
                                    placeholder="请选择线路"
                                    onSelect={(value) => this.getLineId(value)}
                                >
                                    {this.state.lineNameId}
                                </Select>)}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        约租类型
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('rentTyle', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写信息!',
                                            whitespace: true
                                        }
                                    ]
                                })(
                                    <Select
                                        placeholder="请选择类型"
                                        onSelect={(value) => this.whetherSharing(value)}
                                    >
                                        <Option value="true">拼车</Option>
                                        <Option value="false">包车</Option>
                                    </Select>
                                )}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        姓名
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('BillName', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写信息!',
                                            whitespace: true,
                                        }
                                    ]
                                })(<Input autoComplete="off" />)}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        电话
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('CompilePhone', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写信息!',
                                            whitespace: true,
                                        }
                                    ]
                                })(<Input type="number" />)}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        人数
                                    </span>
                                )}
                                hasFeedback>
                                <input style={{ width: '100%', padding: '6px 7px', height: '32px', border: '1px solid #d9d9d9', borderRadius: '4px' }} type="text" type="number" ref="personNumber" onChange={this.overPrice} />
                                {/* {getFieldDecorator('mans', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写信息!',
                                            whitespace: true
                                        }
                                    ]
                                })(<Input type="number" onChange={ this.overPrice } />)} */}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        出发地
                                    </span>
                                )}
                                hasFeedback>
                                <input id="departSite" autoComplete="off" ref="departInput" style={{ width: '100%', padding: '6px 7px', height: '32px', border: '1px solid #d9d9d9', borderRadius: '4px' }} placeholder="请输入上车地点" />
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        目的地
                                    </span>
                                )}
                                hasFeedback>
                                <input id="EndSite" autoComplete="off" ref="endInput" style={{ width: '100%', padding: '6px 7px', height: '32px', border: '1px solid #d9d9d9', borderRadius: '4px' }} placeholder="请输入下车地点" />
                            </FormItem>
                        </Col>
                        <Col span={12}>
                            <FormItem className="BillTime"
                                {...formItemLayout}
                                label="约租时间"
                                hasFeedback>
                                {getFieldDecorator('rentTime', config)(
                                    <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{ width: '100%' }} />
                                )}
                            </FormItem>

                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        价格/人
                                    </span>
                                )}
                                hasFeedback>
                                <input autoComplete="off" style={{ width: '100%', padding: '6px 7px', height: '32px', border: '1px solid #d9d9d9', borderRadius: '4px' }} type="text" ref="onePrice" type="number" onChange={this.overPrice} />
                                {/* {getFieldDecorator('singlePrice', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写信息!',
                                            whitespace: true
                                        }
                                    ]
                                })(<Input type="number" onChange={this.overPrice}/>)} */}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        总价
                                    </span>
                                )}
                                hasFeedback>
                                <input autoComplete="off" style={{ width: '100%', padding: '6px 7px', height: '32px', border: '1px solid #d9d9d9', borderRadius: '4px' }} type="text" ref="TPrice" type="number" onChange={this.overPrice} disabled />
                                {/* {getFieldDecorator('sumPrice', {
                                    rules: [
                                        {
                                            required: true,
                                            message: '请填写信息!',
                                            whitespace: true
                                        }
                                    ]
                                })(<Input type="number" />)} */}
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label={(
                                    <span>
                                        要求
                                    </span>
                                )}
                                hasFeedback>
                                {getFieldDecorator('requires', {
                                    rules: [
                                        {
                                            message: '请填写信息!',
                                            whitespace: true
                                        }
                                    ]
                                })(<Input placeholder="选填" />)}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={24}>
                            <FormItem className="center">
                                <Button onClick={this.handleReset}>重置</Button>{' '}
                                <Button type="primary" htmlType="submit">确定</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        )
    }
}

const RentBill = Form.create()(RentBills);
export default RentBill
